/**
 * 
 */
package org.cnbi.service.impl;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.cnbi.dao.IHandleDao;
import org.cnbi.service.IDashService;
import org.cnbi.utils.convert.OjbectConvertUtil;
import org.cnbi.utils.exception.BusinessException;
import org.cnbi.utils.pojo.dash.ItemBean;
import org.cnbi.utils.pojo.dash.ModelBean;
import org.cnbi.utils.pojo.indicator.ItemUtil;
import org.cnbi.utils.string.StringUtil;
import org.cnbi.utils.tools.Constants;
import org.cnbi.utils.tools.GlobalConstants;
import org.cnbi.utils.tools.SymbolConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * Copyright © 2014中国经邦. All rights reserved.
 * @author 龚佳新
 * @date 2014年5月28日下午8:32:09
 * @cnbi-web
 */
@Service
public class IDashServiceImpl implements IDashService {
	
	protected static  final Log logger = LogFactory.getLog(IDashServiceImpl.class);
	
	@Autowired
	private IHandleDao handleDao;

	/* 
	 * @data 2014年5月28日  复写的方法
	 * @see org.cnbi.service.IDashService#queryBigDicamal(java.lang.String, java.lang.Object)
	 */
	@Override
	@Cacheable(value = "locationSearchCache", key = "#param.cacheKey")//cacheKey
	public BigDecimal queryBigDicamal(String sql,ItemUtil param){
		try{
			BigDecimal result = handleDao.queryBigDicamal(sql, param);
			logger.info("成功缓存了key="+param.getCacheKey()+"指标数据 ");
			return result;
		}catch (Exception e) {
			throw new BusinessException("查询"+param.getCacheKey()+"指标时出错了！ \n"+e.getMessage());
		}
		
	}

	/* 
	 * @data 2014年5月29日  复写的方法
	 * @see org.cnbi.service.IDashService#queryListMapBean(java.lang.String, org.cnbi.utils.pojo.indicator.ItemUtil)
	 */
	@Override
	//@Cacheable(value = "locationSearchCache", key = "#param.cacheKey")//cacheKey
	public List<Map> queryListMapBean(String sql, ItemUtil param) {
		try{
			List<Map> list = handleDao.queryListMapBean(sql, param);
			if(list.size() ==0 || null == list){//如果没有数据 就给初始一个
				 String []idArr = param.getItem().split("\\"+SymbolConstants.COMMON),
						factArr = stringToArray(param.getFact());
				 for (String id : idArr) {
					 Map<String,Object> map = new HashMap<String,Object>();
					 for (String fact : factArr) {
						 if(fact.length()>1){
							 map.put(fact, id);
						 }else{
							 map.put(fact, new BigDecimal(0.00));
						 }
					 }
					 list.add(map);
				}
			}
			return list;
		}catch (Exception e) {
			throw new BusinessException("查询"+param.getCacheKey()+"指标时出错了！ \n"+e.getMessage());
		}
		
	}
	/*for (Map.Entry<String, String> m : bean.entrySet()) {    
	  System.out.println("key:"+m.getKey()+" value"+m.getValue());    
    } */  
	/* 
	 * @data 2014年5月28日  复写的方法
	 * @see org.cnbi.service.IDashService#queryBigDicamal(java.lang.String, java.lang.Object)
	 */
	@Override
	@Cacheable(value = "locationSearchCache", key = "#param.cacheKey")//cacheKey
	public Map queryMapBean(String sql, ItemUtil param,ModelBean model) {//map  25636--yysr
         String factType = model.getFactType(), key = "id";;
		 String [] factArr = factType.split("\\"+SymbolConstants.COMMON);
		 int len  = factArr.length;
		  String [] factASCode = new String[len+1];
		    for (int i=0;i<len;i++) {
		    	factASCode[i] = factArr[i];
		    	factArr[i] = Constants.FACTSPLIT+factArr[i]+" as "+factArr[i];
			}
		    factASCode[len] = key;
		    factType = StringUtil.arrayToDelimitedString(factArr, ",");
		    String subject = model.getSubject();
		   StringBuffer scode = new StringBuffer();
		   List<Object> itemList = model.getQueryItems();
		   Map helpMap = new HashMap();
		   for (Object object : itemList){
			   ItemBean bean = OjbectConvertUtil.getItemBean(object,model);
			   scode.append(bean.getScode()).append(",");
			   helpMap.put(bean.getScode(), bean.getId());
		   }
		   len = scode.length();
		   scode.delete(len-1, len);
		   factType = factType+","+Constants.DIM+SymbolConstants.UNDERLINE+GlobalConstants.DIMMAP.get(subject)+" as "+key;
		   param.setFact(factType);
		   param.setItem(scode.toString());
		   /**
		    * 实施查询 条件成就
		    */
		    sql = sql.replace("as datas","");
		    List<Map> list  = queryListMapBean(sql, param);
		Map resultMap = new HashMap();
		for (String fact : factASCode){
			if(fact.length() == 1){
				Map tempMap = new HashMap();
				 for(Map bean:list){
				   tempMap.put(helpMap.get(bean.get(key)), bean.get(fact));
				 }
				 resultMap.put(fact, tempMap);
			}
		}
		logger.info("queryMapBean方法成功缓存了key="+param.getCacheKey()+"模型指标数据 ");
		return resultMap;
	}
	
	
	
	public String [] stringToArray(String fact){
		String [] arr = fact.split(",");
		for (int i=0,len=arr.length;i<len;i++) {
			arr[i]  = arr[i].split("as")[1].trim();
		}
		return arr;
	}

}
